﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mads.CoreDomain;
using Mads.CoreDomain.Enumerations;

namespace Mads.WcfService
{
  class ClientCashier : ClientUser
  {
    public ClientCashier(TrainBaseConnector trainBaseConnector, User user)
      : base(trainBaseConnector, user)
    {
    }

    public override bool BuyTicket(FreeTicket freeTicket, Station departure,
      Station arrival, string name, string docNumber)
    {
      return BuyTicket(
        freeTicket, departure, arrival, name, docNumber, TicketState.Bought);
    }

    internal bool BuyTicket(Ticket ticket)
    {
      ticket.State = TicketState.Bought;
      return trainBaseConnector.Persist(ticket);
    }

    public bool ReturnTicket(Ticket ticket)
    {
      var adjacentTickets =
        trainBaseConnector.GetAdjacentFreeTickets(ticket).ToList();
      Ticket previous = adjacentTickets.FirstOrDefault(
        x => x.EndStation.ID == ticket.StartStation.ID);
      if (previous != null)
      {
        ticket.StartStation = previous.StartStation;
      }
      Ticket next = adjacentTickets.FirstOrDefault(
        x => x.StartStation.ID == ticket.EndStation.ID);
      if (next != null)
      {
        ticket.EndStation = next.EndStation;
      }

      ticket.State = TicketState.Free;
      ticket.Bought = null;
      ticket.Buyer = null;
      ticket.LogicalID = null;
      ticket.Owner = null;

      if (!trainBaseConnector.Persist(ticket))
      { return false; }
      adjacentTickets.ForEach(x =>
        trainBaseConnector.Delete<Ticket>(x.ID.Value));

      return true;
    }
  }
}